package com.dems.core.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

@Slf4j
public class SHA1Utils {

    public SHA1Utils() {
    }

    private final static String[] hexDigits = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    private static final String SHA1 = "SHA1";

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n = 256 + n;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }


    public static String byteArrayToHexString(byte[] b) {
        StringBuilder resultSb = new StringBuilder();
        for (byte value : b) {
            resultSb.append(byteToHexString(value));
        }
        return resultSb.toString();
    }

    public static String SHA1Encode(String origin) {
        String resultString = null;

        try {
            resultString = origin;
            MessageDigest md = MessageDigest.getInstance(SHA1);
            resultString = byteArrayToHexString(md.digest(resultString.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception ignored) {

        }
        return resultString;
    }

    /**
     * @param data 入参
     * @return 签名字符串
     */
    public static String sign(JSONObject data) {
        data.remove("sign");
        StringBuilder stringBuilder = new StringBuilder();
        try {
            Map<String, String> treeMap = new TreeMap<>();
            //排序得到的字符串
            for (String key : data.keySet()) {
                treeMap.put(key, data.getString(key));
            }
            TreeMap<String, String> sortMap = new TreeMap<>(Comparator.naturalOrder());
            sortMap.putAll(treeMap);
            //排序得到的字符串
            for (Map.Entry<String, String> entry : sortMap.entrySet()) {
                stringBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
        } catch (Exception e) {
            log.error("#############签名失败#########" + e.getMessage(), e);
        }
        return SHA1Encode(stringBuilder.substring(0, stringBuilder.length() - 1));
    }

}
